package org.framework.lazy.cloud.network.heartbeat.server.netty.proxy.http.socket;


import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.common.utils.ChannelAttributeKeyUtils;
import org.framework.lazy.cloud.network.heartbeat.server.netty.proxy.http.NettyHttpClientProxyServerTransfer;
import org.framework.lazy.cloud.network.heartbeat.server.netty.proxy.http.filter.NettyHttpClientProxyServerRealFilter;

import java.util.concurrent.TimeUnit;

/**
 * 服务端渗透服务端 连接真实通道
 */
@Slf4j
public class NettyHttpClientProxyServerRealSocket {
    private static final EventLoopGroup eventLoopGroup = new NioEventLoopGroup();


    /**
     * @param nettyHttpClientProxyServerTransfer 访客信息
     * @param proxyTransferChannel               代理传输通道
     * @param visitorId                          请求ID
     */
    public static void buildRealServer(NettyHttpClientProxyServerTransfer nettyHttpClientProxyServerTransfer,
                                       Channel proxyTransferChannel, String visitorId) {
        try {
            String clientTargetIp = nettyHttpClientProxyServerTransfer.getTargetIp();
            Integer clientTargetPort = nettyHttpClientProxyServerTransfer.getTargetPort();
            byte[] data = nettyHttpClientProxyServerTransfer.getData();

            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
//                     设置读缓冲区为2M
                    .option(ChannelOption.SO_RCVBUF, 2048 * 1024)
//                     设置写缓冲区为1M
                    .option(ChannelOption.SO_SNDBUF, 1024 * 1024)
//                    .option(ChannelOption.TCP_NODELAY, false)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000 * 60)//连接超时时间设置为 60 秒
//                    .option(ChannelOption.SO_BACKLOG, 128)//务端接受连接的队列长度 默认128
//                    .option(ChannelOption.RCVBUF_ALLOCATOR, new NettyRecvByteBufAllocator(1024 * 1024))//用于Channel分配接受Buffer的分配器 默认AdaptiveRecvByteBufAllocator.DEFAULT
                    .option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(1024 * 1024, 1024 * 1024 * 2))
                    .handler(new NettyHttpClientProxyServerRealFilter(nettyHttpClientProxyServerTransfer))

            ;


            bootstrap
                    .connect(clientTargetIp, clientTargetPort)
                    .sync()
                    .addListener((ChannelFutureListener) channelFuture -> {
                        if (channelFuture.isSuccess()) {
                            // 客户端链接真实服务成功 设置自动读写false 等待访客连接成功后设置成true
                            Channel realChannel = channelFuture.channel();
//                            realChannel.config().setOption(ChannelOption.AUTO_READ, false);
                            realChannel.config().setOption(ChannelOption.AUTO_READ, true);

                            log.info("客户端代理服务端,绑定本地服务,IP:{},端口:{} channelID:{} 新建通道成功", clientTargetIp, clientTargetPort, realChannel.id().asLongText());
                            // 缓存当前端口对应的通道、通道池
                            ChannelAttributeKeyUtils.buildNextChannel(realChannel, proxyTransferChannel);
                            ChannelAttributeKeyUtils.buildNextChannel(proxyTransferChannel, realChannel);

                            ChannelAttributeKeyUtils.buildVisitorId(realChannel, visitorId);

                            proxyTransferChannel.config().setOption(ChannelOption.AUTO_READ, true);
                            // 发送数据
                            ByteBuf buf = realChannel.config().getAllocator().buffer(data.length);
                            buf.writeBytes(data);
                            realChannel.writeAndFlush(buf);


                        } else {
                            log.error("客户端代理服务端 无法连接当前网络内的目标IP：【{}】,目标端口:【{}】", clientTargetIp, clientTargetPort);
                            eventLoopGroup.schedule(() -> {
                                buildRealServer(nettyHttpClientProxyServerTransfer, proxyTransferChannel, visitorId);
                            }, 2, TimeUnit.SECONDS);
                        }
                    });


        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}